package util

import (
	"fmt"
	"github.com/EDDYCJY/go-gin-example/pkg/setting"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/google/uuid"
	"github.com/spf13/cast"
	"gopkg.in/gomail.v2"
	"math/rand"
	"strings"
	"time"
)

// Setup Initialize the util
func Setup() {
	jwtSecret = []byte(setting.AppSetting.JwtSecret)
}

func TimeStr2Int(timeStr string, types int) int64 {
	tmp := "2006-01-02 15:04:05"
	if types == 2 {
		tmp = "2006-01-02T15:04:05+08:00"
	}
	res, _ := time.ParseInLocation(tmp, timeStr, time.Local)
	return res.Unix()
}

func GenValidateCode(width int) string {
	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder
	for i := 0; i < width; i++ {
		fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}

func GenNonce() string {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	bytes := make([]byte, 10)
	for i := 0; i < 10; i++ {
		b := r.Intn(26) + 97
		bytes[i] = byte(b)
	}
	s_str := string(bytes)

	o_uuid, _ := uuid.NewRandom()
	s_uuid := o_uuid.String()

	s_nonce := fmt.Sprintf("%v%v%v%v%v%v%x",
		s_uuid[0:8], s_uuid[9:13], s_uuid[14:18], s_uuid[19:23], s_uuid[24:],
		s_str, time.Now().UTC().UnixNano())

	return s_nonce
}

// subject: 邮件标题
func SendMailCode(smtp_host string, smtp_port string, subject string,
	from_name string, from_address string, authCode string, to_address string, body string) error {
	m := gomail.NewMessage()
	m.SetHeader("Subject", subject)
	m.SetHeader("From", from_name+" <"+from_address+">")
	m.SetHeader("To", to_address)
	m.SetBody("text/plain", body)
	d := gomail.NewDialer(smtp_host, cast.ToInt(smtp_port), from_address, authCode)
	err := d.DialAndSend(m)
	return err
}

// 发送短信验证码
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     accessKeyId,
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

func SendPhoneCode(phone string, sign_name string, template_code string, code string,
	access_key_id string, access_key_secret string) (_err error) {
	client, _err := CreateClient(tea.String(access_key_id), tea.String(access_key_secret))
	if _err != nil {
		return _err
	}

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(phone),
		SignName:      tea.String(sign_name),
		TemplateCode:  tea.String(template_code),
		TemplateParam: tea.String("{\"code\":\"" + code + "\"}"),
	}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		_, _err = client.SendSmsWithOptions(sendSmsRequest, &util.RuntimeOptions{})
		if _err != nil {
			return _err
		}

		return nil
	}()

	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		_, _err = util.AssertAsString(error.Message)
		if _err != nil {
			return _err
		}
	}
	return _err
}
